package com.aizuda.easyManagerTool.service.gpt;

import cn.hutool.json.JSONUtil;
import com.aizuda.easyManagerTool.domain.vo.socket.SocketMessageVO;
import com.plexpt.chatgpt.entity.chat.Message;
import com.plexpt.chatgpt.listener.AbstractStreamListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
public class SocketStreamListener extends AbstractStreamListener{

    final WebSocketSession webSocketSession;
    SocketMessageVO socketMessageVO = new SocketMessageVO();
    final static String TYPE = "chartGPT";
    final MessageModel model;

    public SocketStreamListener(WebSocketSession webSocketSession,MessageModel model) {
        this.webSocketSession = webSocketSession;
        this.model = model;
    }

    @Override
    public void onMsg(String s) {
        send(s);
    }

    @Override
    public void onError(Throwable throwable, String s) {
       send(s);
    }

    private void send(String s){
        try {
            Message build = Message.builder().name("ai").role("system").content(s).build();
            // 具体哪个功能
            socketMessageVO.setType(TYPE);
            model.setMsg(build);
            socketMessageVO.setObj(model);
            webSocketSession.sendMessage(new TextMessage(JSONUtil.toJsonStr(socketMessageVO)));
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }


}
